package com.wangcang.widgetlibrary.activity;

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.wangcang.widgetlibrary.R;
import com.wangcang.widgetlibrary.activity.base.BaseActivity;
import com.wangcang.widgetlibrary.adapter.ContactAdapter;
import com.wangcang.widgetlibrary.bean.ContactsBean;
import com.wangcang.widgetlibrary.contacts.ClearEditText;
import com.wangcang.widgetlibrary.contacts.ContactsTools;
import com.wangcang.widgetlibrary.contacts.SectionBar;
import com.wangcang.widgetlibrary.tools.PermissionUtils;
import com.wangcang.widgetlibrary.tools.PinyinUtils;
import com.wangcang.widgetlibrary.tools.ThreadUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 通讯录Activity
 * Created by ShineF on 2017/6/20 0020.
 */

public class ContactsActivity extends BaseActivity implements PermissionUtils.PermissionCallbacks, DialogInterface.OnClickListener, View.OnClickListener, AbsListView.OnScrollListener, TextWatcher, SectionBar.OnTouchLetterChangeListenner {

    private ListView mLvContacts;
    private final int QUARY_CONTACTS_OK = 1;
    private final int CHANGE_OK = 2;
    private SectionBar mSectionBar = null;
    private RelativeLayout mRlSearch;
    private RelativeLayout mRlInput;
    private ClearEditText mEditText;
    private ImageView mBackBt;
    private List<ContactsBean> mDataList;
    private ContactAdapter mAdapter;
    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case QUARY_CONTACTS_OK:
                    List<ContactsBean> mTempList = (List<ContactsBean>) msg.obj;
                    mDataList = filledData(mTempList);
                    mAdapter = new ContactAdapter(mDataList, ContactsActivity.this);
                    mLvContacts.setAdapter(mAdapter);
                    mSectionBar.setOnTouchLetterChangeListenner(ContactsActivity.this);
                    break;
                case CHANGE_OK:
                    List<ContactsBean> changeList = (List<ContactsBean>) msg.obj;
                    mAdapter.updataAdapter(changeList);
                    break;
            }
            return false;
        }
    });

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_contacts);
        init();
    }

    public void init() {
        mLvContacts = (ListView) findViewById(R.id.lv_contacts);
        mSectionBar = (SectionBar) findViewById(R.id.sb_index);
        mRlSearch = (RelativeLayout) findViewById(R.id.rel_serach);
        mRlInput = (RelativeLayout) findViewById(R.id.rel_input);
        mEditText = (ClearEditText) findViewById(R.id.et_serach);
        mBackBt = (ImageView) findViewById(R.id.back_bt);
        mRlInput.setVisibility(View.GONE);
        mRlSearch.setVisibility(View.VISIBLE);
        mRlSearch.setOnClickListener(this);
        mBackBt.setOnClickListener(this);
        mLvContacts.setOnScrollListener(this);
        mEditText.addTextChangedListener(this);
        PermissionUtils.requestPermissions(this, new String[]{Manifest.permission.READ_CONTACTS}, 1);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionUtils.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    public void initData() {
        ThreadUtils.newThread(new Runnable() {
            @Override
            public void run() {
                List<ContactsBean> mDataList = ContactsTools.getSystemContacts(ContactsActivity.this);
                Message msg = Message.obtain();
                msg.what = QUARY_CONTACTS_OK;
                msg.obj = mDataList;
                mHandler.sendMessage(msg);
            }
        });
    }

    private List<ContactsBean> filledData(List<ContactsBean> beanList) {
        for (int i = 0; i < beanList.size(); i++) {
            ContactsBean bean = beanList.get(i);
            String phoneNum = beanList.get(i).getPhone().replaceAll(" ", "");
            phoneNum = phoneNum.replaceAll("-", "");
            if (phoneNum.length() == 14) {
                if ("+86".equals(phoneNum.substring(0, 3))) {
                    phoneNum = phoneNum.substring(3, phoneNum.length());
                }
            }
            bean.setPhone(phoneNum);
            String pinyin = PinyinUtils.getPinyin(beanList.get(i).getName());
            String sortString = pinyin.substring(0, 1).toUpperCase();
            if (sortString.matches("[A-Z]")) {
                bean.setInitials(sortString.toUpperCase());
            } else {
                bean.setInitials("#");
            }
        }
        return beanList;
    }


    /**
     * 搜索列表
     */
    private void filterData(String filterStr) {
        List<ContactsBean> filterDateList = new ArrayList<>();
        if (TextUtils.isEmpty(filterStr)) {
            filterDateList = mDataList;
        } else {
            filterDateList.clear();
            for (ContactsBean bean : mDataList) {
                String name = bean.getName();
                String number = bean.getPhone();
                if (name.indexOf(filterStr.toString()) != -1 || PinyinUtils.getPinyin(name).startsWith(filterStr.toString())) {
                    filterDateList.add(bean);
                } else if (number.indexOf(filterStr.toString()) != -1 || number.startsWith(filterStr.toString())) {
                    filterDateList.add(bean);
                }
            }
        }
        Message msg = Message.obtain();
        msg.what = CHANGE_OK;
        msg.obj = filterDateList;
        mHandler.sendMessage(msg);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        if (requestCode == 1 && perms.size() == 1) {
            initData();
        }
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        if (requestCode == 1) {
            Toast.makeText(this, "拒绝了权限" + perms.get(0), Toast.LENGTH_SHORT).show();
            PermissionUtils.permissionDialog(this, perms, this);
        }
    }

    @Override
    public void onClick(DialogInterface dialog, int which) {
        finish();
        Toast.makeText(this, "请去设置页面开启权限", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.rel_serach) {
            mRlInput.setVisibility(View.VISIBLE);
            mRlSearch.setVisibility(View.GONE);
            showSoftKeyBoard(mEditText);
            mEditText.requestFocus();
        }
        else if (v.getId() == R.id.back_bt) {
            finishActivity();
        }
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        if (scrollState == SCROLL_STATE_TOUCH_SCROLL && TextUtils.isEmpty(mEditText.getText().toString())) {
            mEditText.clearFocus();
            hideSoftKeyBoard(mEditText);
            mRlSearch.setVisibility(View.VISIBLE);
            mRlInput.setVisibility(View.GONE);
        } else {
            mEditText.clearFocus();
            hideSoftKeyBoard(mEditText);
        }
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

    }

    public void hideSoftKeyBoard(EditText editText) {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm.isActive()) {
            imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
        }
    }

    public void showSoftKeyBoard(EditText editText) {
        editText.requestFocus();
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(editText, InputMethodManager.SHOW_FORCED);
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        filterData(s.toString());
    }

    @Override
    public void afterTextChanged(Editable s) {

    }

    @Override
    public void onTouchLetterChange(boolean isTouch, String letter) {
        int pos = mAdapter.getStartPositionOfSection(letter);
        mLvContacts.setSelection(pos);
    }
}
